package com.sjp.myspring.orm.test;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcTest2 {

    public static void main(String[] args) {
        String sql = "SELECT * FROM book";
        List<?> result = select(Book.class, sql);
        result.forEach(System.out::println);
    }

    private static <T> List<T> select(Class<T> clazz, String sql) {

        List<T> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/sjp";
            String username = "root";
            String password = "123456";
            //建立连接
            conn = DriverManager.getConnection(url, username, password);
            //创建语句集
            ps = conn.prepareStatement(sql);
            //执行语句集
            rs = ps.executeQuery();

            int columnCount = rs.getMetaData().getColumnCount();

            while (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rs.getMetaData().getColumnName(i);
                    try {
                        Field field = clazz.getDeclaredField(columnName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(t, rs.getObject(columnName));
                        }
                    } catch (NoSuchFieldException e) {

                    }
                }
                list.add(t);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭结果集，语句集，连接
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        return list;
    }
}
